
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Solution {

    public void delect () throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/dream?characterEncoding=utf-8&&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("666666");
        Connection connection = ((MysqlDataSource)dataSource).getConnection();
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入需要删除的id：");
        int id = scanner.nextInt();
        String sql = "delete from student where id=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.executeUpdate();
        statement.close();
        connection.close();
    }
    public void select () throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/dream?characterEncoding=utf-8&&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("666666");
        Connection connection = ((MysqlDataSource)dataSource).getConnection();
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()) {
            System.out.println(resultSet.getInt("id") +"    " + resultSet.getString("name"));

        }
        resultSet.close();
        statement.close();
        connection.close();
    }
    public void insert ()throws SQLException{
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/dream?characterEncoding=utf-8&&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("666666");
        Connection connection = ((MysqlDataSource)dataSource).getConnection();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入添加学生的id与name(用空格隔开)");
        int id = scanner.nextInt();
        String name = scanner.nextLine();
        String sql = "insert into student values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        statement.executeUpdate();
        statement.close();
        connection.close();
    }

}
